package com.bw.module_home.property.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.lib_common.base.BaseViewModel
import com.bw.module_home.property.model.PropertyEntity
import com.bw.module_home.property.model.PropertyRepository
import com.bw.module_home.property.model.TenantEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject

@HiltViewModel
class PropertyViewModel @Inject constructor(
    private val propertyRepository: PropertyRepository
) : BaseViewModel() {

    val getPropertySuccess = MutableLiveData<PropertyEntity>()
    val getTenantSuccess = MutableLiveData<TenantEntity>()

    fun getPropertyList(regionId: Int) {
        propertyRepository.getPropertyList(regionId)
            .onEach { result ->
                if (result.code == 200) {
                    result.data?.let {
                        getPropertySuccess.value = it
                    }
                } else {
                    Log.e("PropertyViewModel", "获取物业列表失败  ${result.message}")
                }
            }
            .catch { e ->
                Log.e("PropertyViewModel", "获取物业列表异常: ${e.message}")
            }
            .launchIn(viewModelScope)
    }

    fun getTenantList() {
        propertyRepository.getTenantList()
            .onEach { result ->
                if (result.code == 200) {
                    result.data?.let {
                        getTenantSuccess.value = it
                    }
                } else {
                    Log.e("PropertyViewModel", "获取租户列表失败  ${result.message}")
                }
            }
            .catch { e ->
                Log.e("PropertyViewModel", "获取租户列表异常: ${e.message}")
            }
            .launchIn(viewModelScope)
    }
}